<?php
namespace Home\Controller;
use Common\Controller\HomeBaseController;

/**
 * 网站首页
 */
class IndexController extends HomeBaseController {

    // 首页
    public function index(){
        $tid=I('get.tid',0,'intval');

        // 获取标签名
        if($tid>0){
            $tname=D('Tag')->getFieldByTid($tid,'tname');
            $title=$tname;
            $this->assign('title',$title);
            // 如果标签不存在；则返回404页面
            if (empty($tname)) {
                header("HTTP/1.0  404  Not Found");
                $this->display('./Template/default/Home/Public/404.html');
                exit(0);
            }
        }else{
            $tid='all';
        }
        if(!empty($_GET['province'])){
            $location=$_GET['province'];
        }else{
            $location='';
        }
        if(!empty($_GET['city'])){
            $location=$location."|".$_GET['city'];
        }
        if(!empty($_GET['area'])){
            $location=$location."|".$_GET['area'];
        }

        if($location==''){
            $location='all';
        }

        if($this->user['is_admin']==1){
            $is_show='all';
        }else{
            $is_show=1;
        }

        $articles=D('Article')->getPageData($location,$tid,$is_show,0,12);
        $assign=array(
            'articles'=>$articles['data'],
            'page'=>$articles['page'],
            'cid'=>'index'
            );
        $this->assign($assign);
        $this->display();
    }

    // 分类
    public function category(){
        $cid=I('get.cid',0,'intval');
        // 获取分类数据
        $category=D('Category')->getDataByCid($cid);
        // 如果分类不存在；则返回404页面
        if (empty($category)) {
            header("HTTP/1.0  404  Not Found");
            $this->display('./Template/default/Home/Public/404.html');
            exit(0);
        }
        // 获取分类下的学校数据
        $articles=D('Article')->getPageData($cid);
        $assign=array(
            'category'=>$category,
            'articles'=>$articles['data'],
            'page'=>$articles['page'],
            'cid'=>$cid
            );
        $this->assign($assign);
        $this->display();
    }

    // 标签
    public function tag(){
        $tid=I('get.tid',0,'intval');
        // 获取标签名
        $tname=D('Tag')->getFieldByTid($tid,'tname');
        // 如果标签不存在；则返回404页面
        if (empty($tname)) {
            header("HTTP/1.0  404  Not Found");
            $this->display('./Template/default/Home/Public/404.html');
            exit(0);
        }
        // 获取学校数据
        $articles=D('Article')->getPageData('all',$tid);
        $assign=array(
            'articles'=>$articles['data'],
            'page'=>$articles['page'],
            'title'=>$tname,
            'title_word'=>'拥有<span class="b-highlight">'.$tname.'</span>标签的学校',
            'cid'=>'index'
            );
        $this->assign($assign);
        $this->display();
    }

    // 学校内容
    public function article(){
        $aid=I('get.aid',0,'intval');
        $cid=intval(cookie('cid'));
        $tid=intval(cookie('tid'));
        $search_word=cookie('search_word');
        $search_word=empty($search_word) ? 0 : $search_word;
        $read=cookie('read');
        // 判断是否已经记录过aid
        if (array_key_exists($aid, $read)) {
            // 判断点击本篇学校的时间是否已经超过一天
            if ($read[$aid]-time()>=86400) {
                $read[$aid]=time();
                // 学校点击量+1
                M('Article')->where(array('aid'=>$aid))->setInc('click',1);
            }
        }else{
            $read[$aid]=time();
            // 学校点击量+1
            M('Article')->where(array('aid'=>$aid))->setInc('click',1);
        }
        cookie('read',$read,864000);
        switch(true){
            case $cid==0 && $tid==0 && $search_word==(string)0:
                $map=array();
                break;
            case $cid!=0:
                $map=array('cid'=>$cid);
                break;
            case $tid!=0:
                $map=array('tid'=>$tid);
                break;
            case $search_word!==0:
                $map=array('title'=>$search_word);
                break;
        }
        // 获取学校数据
        $article=D('Article')->getDataByAid($aid,$map);
        // 如果学校不存在；则返回404页面
        if (empty($article['current']['aid'])) {
            header("HTTP/1.0  404  Not Found");
            $this->display('./Template/default/Home/Public/404.html');
            exit(0);
        }
        //获取项目集
        $projects=D('Project')->select();
        $this->assign('projects',$projects);

        //获取机构集
        $orgs=D('Org')->select();
        $this->assign('orgs',$orgs);

        // 获取评论数据
        $comment=D('Comment')->getChildData($aid);
        $assign=array(
            'article'=>$article,
            'comment'=>$comment,
            'cid'=>$article['current']['cid'],
            );
        if (!empty($_SESSION['user']['uid'])) {
            $assign['user_email']=M('User')->getFieldByUid($_SESSION['user']['uid'],'email');
        }
        $this->assign('lnglat',$article['current']['lnglat']);
        $this->assign($assign);
        $this->display();
    }

    // 随言碎语
    public function chat(){
        $assign=array(
            'data'=>D('Chat')->getDataByState(0,1),
            'cid'=>'chat'
            );
        $this->assign($assign);
        $this->display();
    }

    // 开源项目
    public function git(){
        $assign=array(
            'cid'=>'git'
            );
        $this->assign($assign);
        $this->display();
    }

    // 站内搜索
    public function search(){
        $search_word=I('get.search_word');
        $articles=D('Article')->getDataByTitle($search_word);
        $assign=array(
            'articles'=>$articles['data'],
            'page'=>$articles['page'],
            'title'=>$search_word,
            'title_word'=>'搜索到的与<span class="b-highlight">'.$search_word.'</span>相关的学校',
            'cid'=>'index'
            );
        $this->assign($assign);
        $this->display('tag');
    }

    // ajax评论学校
    public function ajax_comment(){

        $data=I('post.');
        if(empty($data['content']) || !isset($_SESSION['user']['uid'])){
            die('未登录,或内容为空');
        }else{
            $cmtid=D('Comment')->addData(1);
            echo $cmtid;
        }
    }

    // 评论学校
    public function reply(){

        $data=I('post.');
        if(empty($data['content']) || !isset($_SESSION['user']['uid'])){
            die('未登录,或内容为空');
        }else{
            $cmtid=D('Comment')->addData(1);
            echo $cmtid;
        }
    }

    // 删除评论
    public function delreply(){
        $this->check_admin();
        if(IS_POST) {
            $id=I('post.cid');
            if(!$id){
                $this->error('操作失败');
            }
            D('Comment')->where(array('cmtid'=>$id))->delete();
            $this->success('操作成功');
        }
    }


  // 评论项目
    public function post_comment(){

        $data=I('post.');
        if(empty($data['content']) || !isset($_SESSION['user']['uid'])){
            die('未登录,或内容为空');
        }else{

            $cmtid=D('Comment')->addData(2);
            if($cmtid){
                $data1="<div class='form-group'><div class='col-xs-2 col-sm-1 col-md-1 col-lg-1 b-pic-col'><img class='talk-avatar small' src='";
                $data1=$data1.avatar($this->mid)."'></div><div class='col-xs-10 col-sm-11 col-md-11 col-lg-11 b-content-col b-cc-first'><p class='b-content'><span class='b-user-name'>";
                $data1=$data1.$this->user['username']."</span>：".$data['content']."</p><p class='b-date'><span>刚刚</span></p></div></div>";
                $this->ajaxReturn($data1);
            }

        }

    }

    // 找回密码
    public function resetPassword() {

        if ( IS_POST ) {
            $token      = I('post.token', '', '');
            $password   = I('post.password', '', '');
            $rePassword = I('post.rePassword', '', '');

            empty($password) && $this->error('密码不能为空');
            if ($password !== $rePassword) {
                $this->error('确认密码不正确');
            }

            $condition = array( 'token'=>$token );

            $result = D( 'UserToken' )->getUserToken($condition);

            if ($result) {
                $status = D('User')->setPassword($result['uid'], $password);
                if ($status) {
                    D( 'UserToken' )->where( $condition )->setField( 'status', 1 );
                    $this->success('密码修改成功');
                } else {
                    $this->error('密码修改失败');
                }
            } else {
                $this->error(D('UserToken')->getError(), U('topic/index'));
            }

        } else {
            $token   = I('get.token', '', '');
            $result = D( 'UserToken' )->getUserToken(array( 'token'=>$token, 'type'=>2 ));
            if ($result) {
                $this->assign( 'token', $token );
                $this->display();
            } else {
                $this->error(D('UserToken')->getError(), U('Home/index'));
            }
        }
    }




    //上传头像
    public  function upload() {
        /*
        $upload = new \Org\Util\UploadFile();
        $upload->maxSize = 3292200;
        $upload->allowExts = explode(',', 'jpg,gif,png,jpeg');
        $upload->savePath = 'Upload/avatar/';
        $upload->thumbRemoveOrigin =true;

        if ( !$upload->upload() ) {
            $msg =  $upload->getErrorMsg();
            echo json_encode(array('status'=>0, 'msg'=>$msg));
        }else {
            $info =  $upload->getUploadFileInfo();
            $file = $info[0]['savepath'] . $info[0]['savename'];

            $filename =  convert_uid($_SESSION['user']['uid']);

            move_uploaded_file($file,$filename);

            $avatar =  avatar($_SESSION['user']['uid']);
            echo  json_encode(array('status'=>1, 'avatar'=>$avatar));
        }*/
        //1、检测文件的错误信息，如果是0 就允许上传(保存)
        $filesize=3145728;
        $file_arr=array('jpg','png','gif','JPG','GIF','PNG');

        $err=$_FILES['files']['error'];
        if($err>0){
            if($err==1){
                return '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。';
            }elseif($err==2){
                return '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。 ';
            }elseif($err==3){
                return '文件只有部分被上传。';
            }elseif($err==4){
                return'没有文件上传';
            }elseif($err>=5){
                return '其他错误';
            }
        }
        //2、检测文件的类型,是否是我们需要的(png、gif、jpg)
        $pre=pathinfo($_FILES['files']['name'],PATHINFO_EXTENSION);
        if(!in_array($pre,$file_arr)){
            return '上传的文件类型不符';
        }
        //3、检测文件大小
        if($_FILES['files']['size']>$filesize){
            return '上传的文件太大';
        }
        //4、保存文件

        $file_name =  convert_uid($_SESSION['user']['uid']);
        move_uploaded_file($_FILES['files']['tmp_name'], $file_name);
        $avatar =  avatar($_SESSION['user']['uid']);
        echo  json_encode(array('status'=>1, 'avatar'=>$avatar));

    }


    // 首页
    public function avatar(){

        $this->display();
    }

    //添加学校
    public function add(){

        $this->check_admin();
        if(IS_POST){
            $data=I('post.');;

            if($data['verify']==''){
                $data['verify']=0;
            };
            if(!$data['title']){
                $this->error('学校名称不能为空！');
            }
            if(!$data['beginyear']){
                $this->error('建校年份不能为空！');
            }
            if(!$data['tids']){
                $this->error('请至少选择一个标签');
            }
            if(!$data['city']){
                $this->error('学校所在地区必须完整！');

            }
            if(!$data['address']){
                $this->error('详细地址不能为空！');

            }

            if(!$data['lnglat']){
                $this->error('请点击地图确定学校的位置！');
            }

            if(!$data['acreage']){
                $this->error('对不起，占地面积不能为空！');
            }

            if(!$data['teacher']){
                $this->error('教师数不能为空！');

            }

            if(!$data['salary']){
                $this->error('工资水平不能为空！');

            }

            if(!$data['student']){
                $this->error('学生数不能为空！');

            }

            if(!$data['price']){
                $this->error('学费水平不能为空！');

            }


            if(!$data['content']){
                $this->error('对不起，描述不能为空！');
            }

            $content1 =	strip_tags($data['content']);
            if(str_strlen($content1)>10000){
                $this->error('描述不能超过10000字');
            }

            //检查是否有图片
            $image_path=get_ueditor_image_path($data['content']);
            if(empty($image_path)){
                $this->error('请至少插入一张学校的照片，建议尺寸640*480。');
            }



            if($aid=D('Article')->addData($data)){
                $this->success('学校添加成功',U('Home/index/article',array('aid'=>$aid)));
            }else{
                $this->error(D('Article')->getError());
            }
        }else{
            if(isMobile()){
                $lnglat = I('get.lnglat','','');

               // if($lnglat==''){
                   // $lnglat='116.405467,39.907761';
               // }
            }else{
                $lnglat = getlnglat();
            }

            $this->assign('lnglat',$lnglat);
            $allTag=D('Tag')->getAllData();
            $this->assign('allTag',$allTag);
            $this->display();
        }

    }

    public  function getlocation(){

        $lnglat = I('post.lnglat','','');
        $this->success('操作成功',U('Home/index/add/',array('lnglat'=>$lnglat)));
    }

    //修改学校消息
    public function edit(){
        $this->check_admin();
        if(IS_POST){
            $data=I('post.');


            if(!$data['title']){
                $this->error('学校名称不能为空！');
            }
            if(!$data['beginyear']){
                $this->error('建校年份不能为空！');
            }
            if(!$data['tids']){
                $this->error('请至少选择一个标签');
            }
            if(!$data['city']){
                $this->error('学校所在地区必须完整！');

            }
            if(!$data['address']){
                $this->error('详细地址不能为空！');

            }

            if(!$data['lnglat']){
                $this->error('请点击地图确定学校的位置！');
            }

            if(!$data['acreage']){
                $this->error('对不起，占地面积不能为空！');
            }

            if(!$data['teacher']){
                $this->error('教师数不能为空！');

            }

            if(!$data['salary']){
                $this->error('工资水平不能为空！');

            }

            if(!$data['student']){
                $this->error('学生数不能为空！');

            }

            if(!$data['price']){
                $this->error('学费水平不能为空！');

            }


            if(!$data['content']){
                $this->error('对不起，描述不能为空！');
            }

            $content1 =	strip_tags($data['content']);
            if(str_strlen($content1)>10000){
                $this->error('描述不能超过10000字');
            }

            //检查是否有图片
            $image_path=get_ueditor_image_path($data['content']);
            if(empty($image_path)){
                $this->error('请至少插入一张学校的照片，建议尺寸640*480。');
            }

            $db=D('Article');
            if($db->editData()){
                $this->success('修改成功',U('Home/index/article',array('aid'=>$data['aid'])));
            }else{
                $this->error('修改失败');
            }
        }else{
            $aid=I('aid');
            $article=D('Article')->getDataByAid($aid);

            $allTag=D('Tag')->getAllData();
            $this->assign('allTag',$allTag);
            if(empty($article['lnglat'])){
                $lnglat='116.405467,39.907761';
            }else{
                $lnglat=$article['lnglat'];
            }
            $this->assign('lnglat',$lnglat);
            $this->assign('data',$article);
            $this->display();
        }
    }

    public function addproject(){
        $this->check_admin();
        if(IS_POST) {
            $data = I('post.');
            $aid=$data['aid'];
            $pid=$data['pid'];
            $p_name=$data['p_name'];
            $oid=$data['oid'];
            $father=$data['father'];
            $o_name= $data['o_name'];
            $description= $data['description'];
            $b_time=strtotime($data['b_time']) ;
            $f_time=strtotime( $data['f_time']);

            if ($pid == '') {
                if( $p_name ==''){
                    $this->error('项目不能为空！');
                }
                if ($oid == ''&& $o_name =='') {
                    $this->error('机构不能为空！');
                }
            }
            if($father==''){
                $father = 0;
            }
            if($b_time == ''){
               $this->error('起始时间不能为空！');
            }

            if($f_time == ''){
               $this->error('结束时间不能为空！');
            }

            if (!empty($o_name)){

                $oid=D('Org')->where(array('o_name'=>$o_name))->getField('oid');

                if(empty($oid)){
                    if(str_strlen($o_name)>20){
                        $this->error('机构名称不能超过20字');
                    }


                    $oid=D('Org')->add(array('o_name'=>$o_name));
                }
            }

            if(!empty($p_name)){
                $pid=D('Project')->where(array('p_name'=>$p_name))->getField('pid');
                if(empty($pid)){
                    if(str_strlen($p_name)>20){
                        $this->error('项目名称不能超过20字');
                    }
                    if(str_strlen($description)>30){
                        $this->error('项目描述不能超过30字');
                    }
                    $pid=D('Project')->add(array('oid'=>$oid,'p_name'=>$p_name,'description'=>$description));
                }
            }
            $result=D('ArticleProject')->addData($aid,$pid,$b_time,$f_time,$father);
            if($result){
                $this->success('操作成功');
            }else{
                $this->success('操作失败');
            }

        }
    }

    public function delproject(){
        $this->check_admin();
        if(IS_POST) {
            $id=I('post.id');
            if(!$id){
                $this->error('操作失败');
            }
            D('ArticleProject')->where(array('id'=>$id))->delete();
            $this->success('操作成功');
        }
    }

    public function addgrade(){
        $this->check_admin();
        if(IS_POST) {

            $data = I('post.');
            if(in_array('',$data['grade'])){
                $this->error('年级不能为空！');
            }
            if (count($data['grade']) != count(array_unique($data['grade']))) {
                $this->error('年级不能重复！');
            }
            if(in_array('',$data['g_num'])){
                $this->error('人数不能为空！');
            }
            foreach($data['grade'] as $k=>$v){

                $arr[$k]['grade']=$v;

            }
            foreach($data['g_num'] as $k=>$v){

                $arr[$k]['g_num']=$v;
            }
            D('ArticleGrade')->where(array('aid'=>$data['aid']))->delete();
            $result=D('ArticleGrade')->addData($data['aid'],$arr);
            if($result){
                $data='';
                foreach($arr as $v){
                    $data=$data.'<div class="form-group" style="text-align: center">'.makeoption($v['grade']).'&nbsp;&nbsp; '.$v['g_num'].'</div>';
                };
                $this->ajaxReturn($data);
            }else{
                $this->error('操作失败！');
            }

        }
    }


    public function addfather(){
        $this->check_admin();


        $oid=I('post.oid',0,'intval');


        $list=D('Project')->where(array('oid'=>$oid))->select();
        $data='<div class="form-group"><div class="col-md-offset-1 col-md-2" ></div><div class="col-md-3"><select id="father" name="father" class="form-control"><option value="">选择父项目</option>';
        foreach($list as $v){
            $data=$data.'<option value="'.$v['pid'].'">'.$v['p_name'].'</option>';
        }
        $data=$data.'</select></div></div>';
        $this->ajaxReturn($data);

    }

    public function changestatus(){
        $this->check_admin();
        $aid=I('post.aid',0,'intval');
        $status=I('post.status',0,'intval');
        D('Article')->where(array('aid'=>$aid))->setField('status',$status);
        $this->success('操作成功');

    }

    public function excel(){

        $eid=I('get.eid',0,'intval');

        //Excel表格式,这里简略写了8列
        $letter = array('A','B','C','D','E','F','G','H','I');
        //表头数组
        $tableheader = array('姓名','昵称','性别','年龄','手机','邮箱','身份证号','是否学生','角色');
        $uids=D('EventMember')->where(array('eid'=>$eid))->order('mid')->getField('uid',true);
        foreach ( $uids as $key => $v ){
            $arr=D('User')->where(array('uid'=>$v))->getField('realname,username,gender,contact,email,idcardnum,comefrom');
            if($arr['gender']==1){
                $sex='男';
            }else{
                $sex='女';
            }
            switch($arr['comefrom']){
                case 0:
                    $comefrom='中学生';
                    break;
                case 1:
                    $comefrom='大学生';
                    break;
                case 2:
                    $comefrom='工作3年以下';
                    break;
                case 3:
                    $comefrom='工作3-5年';
                    break;
                case 4:
                    $comefrom='工作6-10年';
                    break;
                case 2:
                    $comefrom='工作10年以上';
                    break;
            }

            $part=D('EventMember')->where(array('eid'=>$eid,'uid'=>$v))->getField('part');
            $birthday=age(strtotime(substr($arr['idcardnum'],6,8)));
            $contact=explode(',',$arr['contact']);
            $data[$key]=array($arr['realname'],$arr['username'],$sex,$birthday,$contact[0],$arr['email'],$arr['idcardnum'],$comefrom,$part);
        }
        $filename='报名表.xls';
        create_xls($data,$letter,$tableheader,$filename);

        //output_xls($data,$filename);

    }

}
